{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ubFUlqz8cj1L"
   },
   "source": [
    "# Tutorial Part 6: Introduction to Graph Convolutions\n",
    "\n",
    "In this tutorial we will learn more about \"graph convolutions.\" These are one of the most powerful deep learning tools for working with molecular data. The reason for this is that molecules can be naturally viewed as graphs.\n",
    "\n",
    "![Molecular Graph](https://github.com/deepchem/deepchem/blob/master/examples/tutorials/basic_graphs.gif?raw=1)\n",
    "\n",
    "Note how standard chemical diagrams of the sort we're used to from high school lend themselves naturally to visualizing molecules as graphs. In the remainder of this tutorial, we'll dig into this relationship in significantly more detail. This will let us get a deeper understanding of how these systems work.\n",
    "\n",
    "## Colab\n",
    "\n",
    "This tutorial and the rest in this sequence are designed to be done in Google colab. If you'd like to open this notebook in colab, you can use the following link.\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepchem/deepchem/blob/master/examples/tutorials/06_Introduction_to_Graph_Convolutions.ipynb)\n",
    "\n",
    "## Setup\n",
    "\n",
    "To run DeepChem within Colab, you'll need to run the following installation commands. This will take about 5 minutes to run to completion and install your environment. You can of course run this tutorial locally if you prefer. In that case, don't run these cells since they will download and install Anaconda on your local machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 156
    },
    "colab_type": "code",
    "id": "EoCLxSnBcj1N",
    "outputId": "d0555806-a13b-4522-c845-c36a7f910fca"
   },
   "outputs": [],
   "source": [
    "!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py\n",
    "import conda_installer\n",
    "conda_installer.install()\n",
    "!/root/miniconda/bin/conda info -e"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 211
    },
    "colab_type": "code",
    "id": "3Jv2cmnW91CF",
    "outputId": "bd523c54-3038-4654-89ad-356ad1e207ca"
   },
   "outputs": [],
   "source": [
    "!pip install --pre deepchem"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BX2erW0ncj1W"
   },
   "source": [
    "# What are Graph Convolutions?\n",
    "\n",
    "Consider a standard convolutional neural network (CNN) of the sort commonly used to process images.  The input is a grid of pixels.  There is a vector of data values for each pixel, for example the red, green, and blue color channels.  The data passes through a series of convolutional layers.  Each layer combines the data from a pixel and its neighbors to produce a new data vector for the pixel.  Early layers detect small scale local patterns, while later layers detect larger, more abstract patterns.  Often the convolutional layers alternate with pooling layers that perform some operation such as max or min over local regions.\n",
    "\n",
    "Graph convolutions are similar, but they operate on a graph.  They begin with a data vector for each node of the graph (for example, the chemical properties of the atom that node represents).  Convolutional and pooling layers combine information from connected nodes (for example, atoms that are bonded to each other) to produce a new data vector for each node.\n",
    "\n",
    "# Training a GraphConvModel\n",
    "\n",
    "Let's use the MoleculeNet suite to load the Tox21 dataset. To featurize the data in a way that graph convolutional networks can use, we set the featurizer option to `'GraphConv'`. The MoleculeNet call returns a training set, a validation set, and a test set for us to use. It also returns `tasks`, a list of the task names, and `transformers`, a list of data transformations that were applied to preprocess the dataset. (Most deep networks are quite finicky and require a set of data transformations to ensure that training proceeds stably.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 89
    },
    "colab_type": "code",
    "id": "JMi2V8Jncj1W",
    "outputId": "56ab5eb6-07be-4d8f-c19b-88d1f73f2f46"
   },
   "outputs": [],
   "source": [
    "import deepchem as dc\n",
    "\n",
    "tasks, datasets, transformers = dc.molnet.load_tox21(featurizer='GraphConv')\n",
    "train_dataset, valid_dataset, test_dataset = datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "QfMW0Y4Kcj1Z"
   },
   "source": [
    "Let's now train a graph convolutional network on this dataset. DeepChem has the class `GraphConvModel` that wraps a standard graph convolutional architecture underneath the hood for user convenience. Let's instantiate an object of this class and train it on our dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 245
    },
    "colab_type": "code",
    "id": "Y9n3jTNHcj1a",
    "outputId": "2caab2e5-5e5a-4f97-a440-753692341d35"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.28185401916503905"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "n_tasks = len(tasks)\n",
    "model = dc.models.GraphConvModel(n_tasks, mode='classification')\n",
    "model.fit(train_dataset, nb_epoch=50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kDDroutEcj1g"
   },
   "source": [
    "Let's try to evaluate the performance of the model we've trained. For this, we need to define a metric, a measure of model performance. `dc.metrics` holds a collection of metrics already. For this dataset, it is standard to use the ROC-AUC score, the area under the receiver operating characteristic curve (which measures the tradeoff between precision and recall). Luckily, the ROC-AUC score is already available in DeepChem. \n",
    "\n",
    "To measure the performance of the model under this metric, we can use the convenience function `model.evaluate()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "MeX-9RNWcj1h",
    "outputId": "642d3f81-33de-46bb-fc7a-8b5edda99881"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set score: {'roc_auc_score': 0.96959686893055}\n",
      "Test set score: {'roc_auc_score': 0.795793783300876}\n"
     ]
    }
   ],
   "source": [
    "metric = dc.metrics.Metric(dc.metrics.roc_auc_score)\n",
    "print('Training set score:', model.evaluate(train_dataset, [metric], transformers))\n",
    "print('Test set score:', model.evaluate(test_dataset, [metric], transformers))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "l-LBxrKN6CMs"
   },
   "source": [
    "The results are pretty good, and `GraphConvModel` is very easy to use. But what's going on under the hood? Could we build GraphConvModel ourselves? Of course! DeepChem provides Keras layers for all the calculations involved in a graph convolution. We are going to apply the following layers from DeepChem.\n",
    "\n",
    "-  `GraphConv` layer: This layer implements the graph convolution. The graph convolution combines per-node feature vectures in a nonlinear fashion with the feature vectors for neighboring nodes.  This \"blends\" information in local neighborhoods of a graph.\n",
    "\n",
    "- `GraphPool` layer: This layer does a max-pooling over the feature vectors of atoms in a neighborhood. You can think of this layer as analogous to a max-pooling layer for 2D convolutions but which operates on graphs instead. \n",
    "\n",
    "- `GraphGather`: Many graph convolutional networks manipulate feature vectors per graph-node. For a molecule for example, each node might represent an atom, and the network would manipulate atomic feature vectors that summarize the local chemistry of the atom. However, at the end of the application, we will likely want to work with a molecule level feature representation. This layer creates a graph level feature vector by combining all the node-level feature vectors.\n",
    "\n",
    "Apart from this we are going to apply standard neural network layers such as [Dense](https://keras.io/api/layers/core_layers/dense/), [BatchNormalization](https://keras.io/api/layers/normalization_layers/batch_normalization/) and [Softmax](https://keras.io/api/layers/activation_layers/softmax/) layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "71_E0CAUcj1n"
   },
   "outputs": [],
   "source": [
    "from deepchem.models.layers import GraphConv, GraphPool, GraphGather\n",
    "import tensorflow as tf\n",
    "import tensorflow.keras.layers as layers\n",
    "\n",
    "batch_size = 100\n",
    "\n",
    "class MyGraphConvModel(tf.keras.Model):\n",
    "\n",
    "  def __init__(self):\n",
    "    super(MyGraphConvModel, self).__init__()\n",
    "    self.gc1 = GraphConv(128, activation_fn=tf.nn.tanh)\n",
    "    self.batch_norm1 = layers.BatchNormalization()\n",
    "    self.gp1 = GraphPool()\n",
    "\n",
    "    self.gc2 = GraphConv(128, activation_fn=tf.nn.tanh)\n",
    "    self.batch_norm2 = layers.BatchNormalization()\n",
    "    self.gp2 = GraphPool()\n",
    "\n",
    "    self.dense1 = layers.Dense(256, activation=tf.nn.tanh)\n",
    "    self.batch_norm3 = layers.BatchNormalization()\n",
    "    self.readout = GraphGather(batch_size=batch_size, activation_fn=tf.nn.tanh)\n",
    "\n",
    "    self.dense2 = layers.Dense(n_tasks*2)\n",
    "    self.logits = layers.Reshape((n_tasks, 2))\n",
    "    self.softmax = layers.Softmax()\n",
    "\n",
    "  def call(self, inputs):\n",
    "    gc1_output = self.gc1(inputs)\n",
    "    batch_norm1_output = self.batch_norm1(gc1_output)\n",
    "    gp1_output = self.gp1([batch_norm1_output] + inputs[1:])\n",
    "\n",
    "    gc2_output = self.gc2([gp1_output] + inputs[1:])\n",
    "    batch_norm2_output = self.batch_norm1(gc2_output)\n",
    "    gp2_output = self.gp2([batch_norm2_output] + inputs[1:])\n",
    "\n",
    "    dense1_output = self.dense1(gp2_output)\n",
    "    batch_norm3_output = self.batch_norm3(dense1_output)\n",
    "    readout_output = self.readout([batch_norm3_output] + inputs[1:])\n",
    "\n",
    "    logits_output = self.logits(self.dense2(readout_output))\n",
    "    return self.softmax(logits_output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "oC20PZiccj1p"
   },
   "source": [
    "We can now see more clearly what is happening.  There are two convolutional blocks, each consisting of a `GraphConv`, followed by batch normalization, followed by a `GraphPool` to do max pooling.  We finish up with a dense layer, another batch normalization, a `GraphGather` to combine the data from all the different nodes, and a final dense layer to produce the global output. \n",
    "\n",
    "Let's now create the DeepChem model which will be a wrapper around the Keras model that we just created. We will also specify the loss function so the model know the objective to minimize."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "31Wr0t2zcj1q"
   },
   "outputs": [],
   "source": [
    "model = dc.models.KerasModel(MyGraphConvModel(), loss=dc.models.losses.CategoricalCrossEntropy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Wz43oG9rcj1j"
   },
   "source": [
    "What are the inputs to this model?  A graph convolution requires a complete description of each molecule, including the list of nodes (atoms) and a description of which ones are bonded to each other.  In fact, if we inspect the dataset we see that the feature array contains Python objects of type `ConvMol`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<deepchem.feat.mol_graphs.ConvMol at 0x14d0b1650>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_dataset.X[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Models expect arrays of numbers as their inputs, not Python objects.  We must convert the `ConvMol` objects into the particular set of arrays expected by the `GraphConv`, `GraphPool`, and `GraphGather` layers.  Fortunately, the `ConvMol` class includes the code to do this, as well as to combine all the molecules in a batch to create a single set of arrays.\n",
    "\n",
    "The following code creates a Python generator that given a batch of data generates the lists of inputs, labels, and weights whose values are Numpy arrays. `atom_features` holds a feature vector of length 75 for each atom. The other inputs are required to support minibatching in TensorFlow. `degree_slice` is an indexing convenience that makes it easy to locate atoms from all molecules with a given degree. `membership` determines the membership of atoms in molecules (atom `i` belongs to molecule `membership[i]`). `deg_adjs` is a list that contains adjacency lists grouped by atom degree. For more details, check out the [code](https://github.com/deepchem/deepchem/blob/master/deepchem/feat/mol_graphs.py)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "o-cPAG0I8Tc4"
   },
   "outputs": [],
   "source": [
    "from deepchem.metrics import to_one_hot\n",
    "from deepchem.feat.mol_graphs import ConvMol\n",
    "import numpy as np\n",
    "\n",
    "def data_generator(dataset, epochs=1):\n",
    "  for ind, (X_b, y_b, w_b, ids_b) in enumerate(dataset.iterbatches(batch_size, epochs,\n",
    "                                                                   deterministic=False, pad_batches=True)):\n",
    "    multiConvMol = ConvMol.agglomerate_mols(X_b)\n",
    "    inputs = [multiConvMol.get_atom_features(), multiConvMol.deg_slice, np.array(multiConvMol.membership)]\n",
    "    for i in range(1, len(multiConvMol.get_deg_adjacency_lists())):\n",
    "      inputs.append(multiConvMol.get_deg_adjacency_lists()[i])\n",
    "    labels = [to_one_hot(y_b.flatten(), 2).reshape(-1, n_tasks, 2)]\n",
    "    weights = [w_b]\n",
    "    yield (inputs, labels, weights)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VSTbjm9Hcj1v"
   },
   "source": [
    "Now, we can train the model using `fit_generator(generator)` which will use the generator we've defined to train the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 245
    },
    "colab_type": "code",
    "id": "59WW4rhwcj1w",
    "outputId": "660ecb20-a2f4-4ae5-e0c8-bc72e309ee72"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.21941944122314452"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit_generator(data_generator(train_dataset, epochs=50))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "skrL9YEEcj13"
   },
   "source": [
    "Now that we have trained our graph convolutional method, let's evaluate its performance. We again have to use our defined generator to evaluate model performance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "f3prNsgGcj14",
    "outputId": "dc95fbba-f5bf-4f7b-8d56-efdc37345d80",
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set score: {'roc_auc_score': 0.8425638289185731}\n",
      "Test set score: {'roc_auc_score': 0.7378436684114341}\n"
     ]
    }
   ],
   "source": [
    "print('Training set score:', model.evaluate_generator(data_generator(train_dataset), [metric], transformers))\n",
    "print('Test set score:', model.evaluate_generator(data_generator(test_dataset), [metric], transformers))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tvOYgj52cj16"
   },
   "source": [
    "Success! The model we've constructed behaves nearly identically to `GraphConvModel`. If you're looking to build your own custom models, you can follow the example we've provided here to do so. We hope to see exciting constructions from your end soon!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "collapsed": true,
    "id": "j1FrVn88cj17"
   },
   "source": [
    "# Congratulations! Time to join the Community!\n",
    "\n",
    "Congratulations on completing this tutorial notebook! If you enjoyed working through the tutorial, and want to continue working with DeepChem, we encourage you to finish the rest of the tutorials in this series. You can also help the DeepChem community in the following ways:\n",
    "\n",
    "## Star DeepChem on [GitHub](https://github.com/deepchem/deepchem)\n",
    "This helps build awareness of the DeepChem project and the tools for open source drug discovery that we're trying to build.\n",
    "\n",
    "## Join the DeepChem Gitter\n",
    "The DeepChem [Gitter](https://gitter.im/deepchem/Lobby) hosts a number of scientists, developers, and enthusiasts interested in deep learning for the life sciences. Join the conversation!"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "name": "04_Introduction_to_Graph_Convolutions.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
